<script setup lang="ts">

import JsonEditor from "@/components/JsonEditor.vue";
import CodeReadOnly from "@/components/CodeReadOnly.vue";
import {onMounted, reactive, ref} from "vue";
import {useTestCaseStore} from "@/stores/test-case.ts";
import {useProblemStore} from "@/stores/problem.ts";
import {ElMessage} from "element-plus";

const code = `[
  {
    "input": "1",
    "output": "1"
  },
  {
    "input": {
      "name": "张三",
      "age": 20
    },
    "output": [1, 2, 3]
  },
  {
    "input": [
      {
        "name": "李四"
      },
      20
    ],
    "output": {
      "food": "草莓"
    }
  }
]`

const testCaseForm = reactive({
  problemId: '',
  testCase: ''
})

const testCaseStore = useTestCaseStore();
const problemStore = useProblemStore();
const jsonEditorRef = ref<InstanceType<typeof JsonEditor> | null>(null)


onMounted(async function () {
  testCaseForm.problemId = problemStore.problemId
  if (testCaseStore.testCase !== testCaseForm.problemId) {
    try {
      await testCaseStore.initTestCase(testCaseForm.problemId)
    } catch (e) {

    }
  }
  testCaseForm.testCase = testCaseStore.testCase
  if (jsonEditorRef.value) {
    jsonEditorRef.value.setCode(testCaseForm.testCase)
  }
})

async function saveTestCase() {
  if (jsonEditorRef.value) {
    testCaseForm.testCase = jsonEditorRef.value.code
  }
  try {
    if (testCaseStore.testCase.trim() === '') {
      await testCaseStore.saveTestCase(testCaseForm.problemId, testCaseForm.testCase)
    } else {
      await testCaseStore.updateTestCase(testCaseForm.problemId, testCaseForm.testCase)
    }
    ElMessage({
      message: '保存成功',
      type: 'success',
    })
  } catch (e:any) {
    ElMessage({
      message: e,
      type: 'error',
    })
  }

}

</script>

<template>
  <div class="container">
    <div class="top">
      <div class="left">
        <JsonEditor ref="jsonEditorRef"/>
      </div>
      <div class="right">
        <div class="top">
          <el-alert title="请以json数组格式编写测试用例，每个json对象有且必须有input和output两个字段, 参考如下" type="info" :closable="false" />
        </div>
        <div class="bottom"><CodeReadOnly :code="code"/></div>
      </div>
    </div>
    <div class="bottom">
      <el-button type="primary" @click="saveTestCase()">
        保存
        <el-icon class="el-icon--right">
          <Upload/>
        </el-icon>
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  .top {
    display: flex;
    .left {
      width: 600px;
      height: 600px;
      margin-right: 30px;
    }
    .right {
      width: 350px;
      height: 600px;
      display: flex;
      flex-wrap: wrap;
      .bottom {
        width: 350px;
      }
    }
  }
  .bottom {
    width: 600px;
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>